package com.sdu.cloudservice.service.impl;

import com.sdu.cloudservice.dao.InstanceInfoDao;
import com.sdu.cloudservice.dao.SpiderHistoryDao;
import com.sdu.cloudservice.dto.Envelope;
import com.sdu.cloudservice.entity.InstanceInfoEntity;
import com.sdu.cloudservice.service.GetPriceInfoService;
import com.sdu.cloudservice.service.SpiderService;
import com.sdu.cloudservice.service.SpiderStatus;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by zekdot on 19-6-23.
 * @author
 * ZMX 最后两个方法
 */
@Service
public class SpiderServiceImpl implements SpiderService {
    @Autowired
    private SpiderHistoryDao spiderHistoryDao;
    @Autowired
    private InstanceInfoDao instanceInfoDao;

    @Autowired
    private GetPriceInfoService getPriceInfoService;

    @Override
    public Envelope getCurrentWorkingStatus() {
        return new Envelope(SpiderStatus.getCurrentWorkingJson());
    }

    @Override
    public Envelope getHistoryRecord(int page) {
        int historyNum = spiderHistoryDao.getPageNumber();
//        int pageNum = historyNum/spiderHistoryDao.onePage - ;
//        if(page<0||page>pageNum)
//            return new Envelope(8,"非法页数",null);
        return new Envelope(spiderHistoryDao.getHistoryByPage(page));
    }

    /**
     * 获取页数
     *
     * @return
     */
    @Override
    public Envelope getHistoryNumber() {
        int historyNum = spiderHistoryDao.getPageNumber();
        int pageNum = historyNum;
        return new Envelope(pageNum);
    }

    @Override
    public Envelope updateFrequency(int frequency) {
        SpiderStatus.fraquency = frequency;
        return Envelope.success;
    }

    @Override
    public Envelope getRegions() {
        Map<String,Object> map=new HashMap();
        List<InstanceInfoEntity> list = instanceInfoDao.getInstanceByLevel(0);
        map.put("valid",list);
        List<InstanceInfoEntity> listi=instanceInfoDao.getInstanceByLevel(100);
        map.put("invalid",listi);
        map.put("frequency",SpiderStatus.fraquency);
        return new Envelope(map);
    }

    @Override
    public Envelope updateRegionValid(String jsonArray, int level) {
        JSONArray array = JSONArray.fromObject(jsonArray);
        int n=array.size();
//        System.out.println(n);
        for(int i=0;i<n;i++){
            System.out.println("set " + array.get(i).toString() + " to " + level);
//            System.out.println();
            instanceInfoDao.updateLevelById(level,array.get(i).toString());
        }
        return Envelope.success;
    }

//    @Override
//    public Envelope forceToWork() {
//        if(SpiderStatus.isWorking){
//            return new Envelope(1,"爬虫正在工作当中!",null);
//        }
//        // getPriceInfoService.updatePrice();
//        return Envelope.success;
//    }
}
